.PHONY:all clean

# target name
TARGET = m_ring_fifo
# cross compiler prefix
COMPILER_PREFIX =
# output directory
BUILD_DIR = $(shell pwd)/build
# user custom actions(shell cmd, use && to separate multiple instructions)
USER_CUSTOM_ACTIONS =

# C sources
C_SOURCES =
C_SOURCES += $(wildcard *.c)
# C includes
C_INCLUDES =
C_INCLUDES += $(addprefix -I,$(dir $(C_SOURCES)))

# C compile option
CFLAGS =
CFLAGS += -O3 -Wall -g $(C_INCLUDES)
# C link option
LDFLAGS =
LDFLAGS += -lpthread

# C sources directories
C_SRCS_DIR = $(dir $(C_SOURCES))

GREEN        := $(shell echo "\033[32m")
BRIGHT_GREEN := $(shell echo "\033[32;1m")
NORMAL       := $(shell echo "\033[0m")

CC        = $(COMPILER_PREFIX)gcc
LD        = $(COMPILER_PREFIX)ld
STRIP     = $(COMPILER_PREFIX)strip
SIZE      = $(COMPILER_PREFIX)size

OBJECTS = $(addprefix $(BUILD_DIR)/Objects/,$(C_SOURCES:.c=.o))
vpath %.c $(sort $(dir $(C_SOURCES)))

all:$(BUILD_DIR)/$(TARGET) USER_CUSTOM

$(BUILD_DIR)/Objects/%.o: %.c
	@-$(shell mkdir -p $(dir $@))
	@$(CC) -c $(CFLAGS) $< -o $@
	@echo "$(GREEN)building$(NORMAL) object $(<:.c=.o)"

$(BUILD_DIR)/$(TARGET).debug: $(OBJECTS)
	@$(CC) $^ $(LDFLAGS) -o $@
	@echo "$(BRIGHT_GREEN)linking$(NORMAL) executable $@"
	@echo "\n--------------------------------------------------------------------------------------------"
	@$(SIZE) $@
	@echo "--------------------------------------------------------------------------------------------\n"

$(BUILD_DIR)/$(TARGET): $(BUILD_DIR)/$(TARGET).debug
	@$(STRIP) -s $< -o $@

USER_CUSTOM: $(BUILD_DIR)/$(TARGET)
ifdef USER_CUSTOM_ACTIONS
	@echo "perform user custom actions:$(USER_CUSTOM_ACTIONS)"
	@echo "$(shell $(USER_CUSTOM_ACTIONS))"
endif

clean:
	@-rm -rf $(BUILD_DIR)